package codec

import (
	"google.golang.org/protobuf/proto"
	"io"
)

type ProtoCodec struct {
	buf       []byte
	writer    io.Writer
	reader    io.Reader
	serialize *ProtoSerialize
}

func (p *ProtoCodec) Encode(m interface{}) error {
	var (
		n   int
		err error
	)
	defer p.serialize.pool.Put(p)
	if p.buf, err = proto.Marshal(m.(proto.Message)); err != nil {
		return err
	}

	n, err = p.writer.Write(p.buf)

	if n < len(p.buf) {
		return io.ErrShortWrite
	}

	return err
}

func (p *ProtoCodec) Decode(m interface{}) (err error) {
	defer p.serialize.pool.Put(p)
	if p.buf, err = io.ReadAll(p.reader); err != nil {
		return err
	}

	if err = proto.Unmarshal(p.buf, m.(proto.Message)); err != nil {
		return err
	}

	return err
}
